package sxe.core.cs511.team2_2;

import snobject.*;
import step.EvaluationFailure;
import step.FunctionWrapper;
import step.exceptions.ResourceUnavailableException;
import java.util.*;

/** OVERVIEW:  A class that defines the opcode storetable.  This opcode will take as an argument a data Object to 
 *  store and will store this object in memory.  At a fixed 1 minute granularity, this method will store all data records in memory
 *  to a SQL database using the current time as a key and will clear the memory region. 
 *  The abstraction function is AF(c) = {a structure containing data Objects in memory}.  
 *  The representation invariant is that the structure can not contain null values.
 * @author lisap
 *
 */

public class slidingbuffer extends FunctionWrapper {
	
	private snStruct struct = new snStruct();
	private int count = 0;
	private int width = 1;

	/** EFFECTS:  This method takes a data Object as an argument and puts it into a memory region.
	 *  At a fixed 1 minute granularity, this method dumps all data records into a SQL database and clears the shared memory region.
	 * This method is called when this opcode is called in a STEP program.
	 * @param arg a data object to be stored
	 * @return true if the data object was sucessfully stored, false if it was not
	 * @throws EvaluationFailure
	 */
	public snObject Call(snObjectArgList arg) throws EvaluationFailure, ResourceUnavailableException{
		
		struct.put(new snString("" + count), arg.popObject());
		
		Calendar cal = Calendar.getInstance();
		long time = cal.getTimeInMillis();
		/*
		 if (nexttime == 0) // if this is the first time this function is called, set nexttime appropriately
			nexttime = (long)(time /1000) * 1000 + 1000;
		*/
		System.out.println("Caching (" + count + ").  current time "+ time );
		
		if (count >= width){
			struct.remove("" + (count-width));
			System.out.println("Clearing (" + (count-width) + ").  current time "+ time );
			System.out.println("New size of struct is : " + struct.size());
		}
		count++;
		return struct;
	}
	
}
